<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>AI简历评分结果</title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <style>
    body {
      background-color: #f8f9fa;
      font-family: 'Arial', sans-serif;
    }
    .result-container {
      max-width: 900px;
      margin: 30px auto;
      background-color: white;
      border-radius: 15px;
      box-shadow: 0 5px 25px rgba(0, 0, 0, 0.1);
      padding: 40px;
    }
    .score-card {
      background: linear-gradient(135deg, #3f51b5, #2196F3);
      color: white;
      border-radius: 12px;
      padding: 30px;
      text-align: center;
      margin-bottom: 40px;
      box-shadow: 0 10px 20px rgba(63, 81, 181, 0.2);
    }
    .score-value {
      font-size: 72px;
      font-weight: bold;
      margin: 15px 0;
      text-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
    }
    .section {
      margin-bottom: 35px;
      padding: 25px;
      background-color: #fff;
      border-radius: 10px;
      box-shadow: 0 3px 15px rgba(0, 0, 0, 0.05);
    }
    .section-title {
      color: #3f51b5;
      font-weight: bold;
      margin-bottom: 20px;
      padding-bottom: 10px;
      border-bottom: 2px solid #eee;
    }
    .aspect-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
      padding: 12px 15px;
      background-color: #f9f9f9;
      border-radius: 8px;
      transition: all 0.3s;
    }
    .aspect-item:hover {
      background-color: #f0f7ff;
      transform: translateX(5px);
    }
    .aspect-name {
      font-weight: bold;
      color: #333;
    }
    .aspect-score {
      font-weight: bold;
      color: #3f51b5;
    }
    .progress-container {
      height: 10px;
      background-color: #e0e0e0;
      border-radius: 5px;
      margin-top: 8px;
      overflow: hidden;
    }
    .progress-fill {
      height: 100%;
      background: linear-gradient(90deg, #4CAF50, #8BC34A);
      border-radius: 5px;
      transition: width 1s ease-out;
    }
    .feedback-item {
      background-color: #f5f5f5;
      padding: 20px;
      border-radius: 8px;
      margin-bottom: 20px;
    }
    .feedback-title {
      font-weight: bold;
      color: #3f51b5;
      margin-bottom: 15px;
      font-size: 18px;
    }
    .improvement-list {
      padding-left: 20px;
    }
    .improvement-list li {
      margin-bottom: 10px;
      position: relative;
      padding-left: 25px;
    }
    .improvement-list li:before {
      content: "•";
      color: #3f51b5;
      font-size: 20px;
      position: absolute;
      left: 0;
      top: -2px;
    }
    .back-btn {
      background-color: #3f51b5;
      color: white;
      border: none;
      padding: 12px 30px;
      border-radius: 8px;
      cursor: pointer;
      font-size: 16px;
      transition: all 0.3s;
      display: block;
      margin: 40px auto 0;
      box-shadow: 0 4px 10px rgba(63, 81, 181, 0.3);
    }
    .back-btn:hover {
      background-color: #303F9F;
      transform: translateY(-2px);
      box-shadow: 0 6px 15px rgba(63, 81, 181, 0.4);
    }
    .resume-preview {
      background-color: #f9f9f9;
      border: 1px solid #eee;
      border-radius: 8px;
      padding: 15px;
      max-height: 300px;
      overflow-y: auto;
      font-family: 'Courier New', monospace;
      white-space: pre-wrap;
    }
    .loading-container {
      text-align: center;
      padding: 50px;
    }
    .loading-spinner {
      border: 4px solid rgba(0, 0, 0, 0.1);
      border-left-color: #3f51b5;
      border-radius: 50%;
      width: 40px;
      height: 40px;
      animation: spin 1s linear infinite;
      margin: 0 auto 20px;
    }
    @keyframes spin {
      to { transform: rotate(360deg); }
    }
  </style>
</head>
<body>
<div class="result-container" id="resultContainer">
  <div class="loading-container" id="loadingIndicator">
    <div class="loading-spinner"></div>
    <p>正在生成AI评分结果，请稍候...</p>
  </div>

  <div id="resultContent" style="display: none;">
    <div class="score-card">
      <h1>AI简历评分结果</h1>
      <div class="score-value" id="totalScore">0</div>
      <div>满分100分</div>
    </div>

    <div class="section">
      <h3 class="section-title">各项评分</h3>
      <div class="aspect-item">
        <span class="aspect-name">内容完整性</span>
        <span class="aspect-score"><span id="contentScore">0</span>/100</span>
      </div>
      <div class="progress-container">
        <div class="progress-fill" id="contentProgress"></div>
      </div>

      <div class="aspect-item">
        <span class="aspect-name">格式规范性</span>
        <span class="aspect-score"><span id="formatScore">0</span>/100</span>
      </div>
      <div class="progress-container">
        <div class="progress-fill" id="formatProgress"></div>
      </div>

      <div class="aspect-item">
        <span class="aspect-name">语言表达</span>
        <span class="aspect-score"><span id="languageScore">0</span>/100</span>
      </div>
      <div class="progress-container">
        <div class="progress-fill" id="languageProgress"></div>
      </div>

      <div class="aspect-item">
        <span class="aspect-name">专业技能展示</span>
        <span class="aspect-score"><span id="skillsScore">0</span>/100</span>
      </div>
      <div class="progress-container">
        <div class="progress-fill" id="skillsProgress"></div>
      </div>

      <div class="aspect-item">
        <span class="aspect-name">项目经验</span>
        <span class="aspect-score"><span id="experienceScore">0</span>/100</span>
      </div>
      <div class="progress-container">
        <div class="progress-fill" id="experienceProgress"></div>
      </div>
    </div>

    <div class="section">
      <h3 class="section-title">AI反馈与建议</h3>
      <div class="feedback-item">
        <div class="feedback-title">优点</div>
        <ul class="improvement-list" id="strengthsList"></ul>
      </div>

      <div class="feedback-item">
        <div class="feedback-title">改进建议</div>
        <ul class="improvement-list" id="improvementsList"></ul>
      </div>
    </div>

    <div class="section">
      <h3 class="section-title">简历内容摘要</h3>
      <div class="resume-preview" id="resumePreview"></div>
    </div>

    <button class="back-btn" id="backButton">
      <i class="fa fa-arrow-left"></i> 返回简历分析
    </button>
  </div>
</div>

<script>
  document.addEventListener('DOMContentLoaded', function() {
    const loadingIndicator = document.getElementById('loadingIndicator');
    const resultContent = document.getElementById('resultContent');
    const backButton = document.getElementById('backButton');

    {{ edit_1 }}
    // 从localStorage获取简历内容（替换原URL参数获取方式）
    const resumeContent = localStorage.getItem('pdfTextContent') || '';

    if (!resumeContent) {
      loadingIndicator.innerHTML = `
                <div class="alert alert-danger">
                    <h4>数据加载失败</h4>
                    <p>未找到简历内容，请重新上传简历</p>
                    <button class="btn btn-primary mt-3" onclick="window.location.href='/chat'">返回上传</button>
                </div>
            `;
      return;
    }

    // 调用AI生成评分结果
    async function generateScore(resumeText) {
      try {
        const response = await fetch('/api/analyze-resume', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            resumeText: resumeText
          })
        });

        if (!response.ok) {
          throw new Error(`请求失败: ${response.status}`);
        }

        const result = await response.json();
        return result;
      } catch (error) {
        console.error('获取评分失败:', error);
        throw error;
      }
    }

    // 动画显示数字
    function animateValue(id, start, end, duration) {
      const obj = document.getElementById(id);
      let startTimestamp = null;
      const step = (timestamp) => {
        if (!startTimestamp) startTimestamp = timestamp;
        const progress = Math.min((timestamp - startTimestamp) / duration, 1);
        obj.innerHTML = Math.floor(progress * (end - start) + start);
        if (progress < 1) {
          window.requestAnimationFrame(step);
        }
      };
      window.requestAnimationFrame(step);
    }

    // 渲染评分结果
    async function renderResult() {
      try {
        // 调用AI生成评分
        const scoreResult = await generateScore(resumeContent);

        // 隐藏加载指示器，显示结果内容
        loadingIndicator.style.display = 'none';
        resultContent.style.display = 'block';

        // 动画显示总分
        animateValue('totalScore', 0, scoreResult.score, 1000);

        // 设置各项评分
        document.getElementById('contentScore').textContent = scoreResult.scores.content;
        document.getElementById('formatScore').textContent = scoreResult.scores.format;
        document.getElementById('languageScore').textContent = scoreResult.scores.language;
        document.getElementById('skillsScore').textContent = scoreResult.scores.skills;
        document.getElementById('experienceScore').textContent = scoreResult.scores.experience;

        // 动画显示进度条
        setTimeout(() => {
          document.getElementById('contentProgress').style.width = scoreResult.scores.content + '%';
          document.getElementById('formatProgress').style.width = scoreResult.scores.format + '%';
          document.getElementById('languageProgress').style.width = scoreResult.scores.language + '%';
          document.getElementById('skillsProgress').style.width = scoreResult.scores.skills + '%';
          document.getElementById('experienceProgress').style.width = scoreResult.scores.experience + '%';
        }, 300);

        // 填充优点列表
        const strengthsList = document.getElementById('strengthsList');
        if (scoreResult.strengths && scoreResult.strengths.length > 0) {
          scoreResult.strengths.forEach(strength => {
            const li = document.createElement('li');
            li.textContent = strength;
            strengthsList.appendChild(li);
          });
        } else {
          strengthsList.innerHTML = '<li>AI未识别到明显优点</li>';
        }

        // 填充改进建议列表
        const improvementsList = document.getElementById('improvementsList');
        if (scoreResult.improvements && scoreResult.improvements.length > 0) {
          scoreResult.improvements.forEach(improvement => {
            const li = document.createElement('li');
            li.textContent = improvement;
            improvementsList.appendChild(li);
          });
        } else {
          improvementsList.innerHTML = '<li>AI未提供改进建议</li>';
        }

        // 填充简历摘要
        document.getElementById('resumePreview').textContent =
                resumeContent.length > 500
                        ? resumeContent.substring(0, 500) + '...'
                        : resumeContent;

      } catch (error) {
        console.error('加载评分结果失败:', error);
        loadingIndicator.innerHTML = `
                    <div class="alert alert-danger">
                        <h4>评分生成失败</h4>
                        <p>${error.message}</p>
                        <button class="btn btn-primary mt-3" onclick="window.history.back()">返回</button>
                    </div>
                `;
      }
    }

    // 返回按钮事件
    backButton.addEventListener('click', function() {
      window.history.back();
    });

    // 初始化渲染
    renderResult();
  });   // 真正解析PDF文件（使用pdf.js）
  function parseRealPdfFile(file) {
    return new Promise((resolve, reject) => {
      const fileReader = new FileReader();
      fileReader.onload = function() {
        const typedArray = new Uint8Array(this.result);
        pdfjsLib.getDocument(typedArray).promise.then(pdf => {
          let totalPages = pdf.numPages;
          let pagesText = [];
          let loadedPages = 0;

          for (let i = 1; i <= totalPages; i++) {
            pdf.getPage(i).then(page => {
              page.getTextContent().then(textContent => {
                let pageText = textContent.items.map(item => item.str).join(' ');
                pagesText.push(pageText);
                loadedPages++;

                if (loadedPages === totalPages) {
                  const fullText = pagesText.join('\n');
                  resolve({
                    name: file.name,
                    size: file.size,
                    content: fullText
                  });
                }
              }).catch(err => {
                reject(err);
              });
            }).catch(err => {
              reject(err);
            });
          }
        }).catch(err => {
          reject(err);
        });
      };
      fileReader.onerror = function() {
        reject(new Error('文件读取失败'));
      };
      fileReader.readAsArrayBuffer(file);
    });
  }

  {{ edit_1 }}
  // 处理文件上传
  fileUploadArea.addEventListener('click', function() {
    uploadFile.click();
  });

  uploadFile.addEventListener('change', async function(event) {
    const file = event.target.files[0];
    if (file && file.type === 'application/pdf') {
      appendMessage(`正在解析PDF文件: ${file.name}`, false);

      try {
        const pdfData = await parseRealPdfFile(file);
        pdfTextContent = pdfData.content;

        // 存储PDF内容到localStorage
        localStorage.setItem('pdfTextContent', pdfTextContent);

        appendMessage(`PDF解析成功，共${pdfData.content.length}字符。现在可以生成评分了！`, false);
        viewResultBtn.disabled = false; // 启用评分按钮
      } catch (error) {
        showError(`PDF解析失败: ${error.message}`);
      }
    }
  });
</script>
</body>
</html>
